package com.example.streamresponse.controller;

import com.example.streamresponse.entity.Member;
import com.example.streamresponse.repository.MemberRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;


@Tag(name = "会员")
@RestController
@RequestMapping(value = "/api/member")
@RequiredArgsConstructor
@Slf4j
public class MemberController {
    private final MemberRepository memberRepository;
    @Operation(summary = "获取所有会员")
    @GetMapping
    public Flux<Member> getAll() {
        return memberRepository.findAll();
    }

    @Operation(summary = "名称查找")
    @GetMapping(value = "/{name}")
    public Mono<Member> getOne(@PathVariable String name) {
        return memberRepository.findByName(name);
    }

    @Operation(summary = "创建会员")
    @PostMapping
    public Mono<Member> createMember(@RequestBody Member member) {
        return memberRepository.save(member);
    }

    @Operation(summary = "xxx")
    @PostMapping(value = "/{number}")
    public Flux<Member> createMembers(@PathVariable int number) {
        return generateRandomMember(number).subscribeOn(Schedulers.boundedElastic());
    }

    private Flux<Member> generateRandomMember(int number) {
        return Mono.fromSupplier(
                        () -> Member.builder().name(RandomStringUtils.randomAlphabetic(5)).build())
                .flatMap(memberRepository::save)
                .repeat(number);
    }

    @Operation(summary = "更新")
    @PutMapping
    public Mono<Member> updateMember(@RequestBody Member member) {
        return memberRepository
                .findByName(member.getName())
                .flatMap(memberResult -> memberRepository.save(member));
    }

    @Operation(summary = "删除")
    @DeleteMapping
    public Mono<Void> deleteMember(@RequestBody Member member) {
        return memberRepository.deleteById(member.getId());
    }

}
